# Create your views here.
from EH.mine.models import *
from basic.blog.models import Post
from django.shortcuts import render_to_response
from django.template import RequestContext
from BeautifulSoup import BeautifulSoup
import re,sys,urllib2
import google
from mechanize import Browser
from difflib import get_close_matches
from django.core.exceptions import *
from EH.life.models import Entry

def getter(request):
	NUM_RESPONSES = 4
	a = re.compile('<\s*br\s*//*>\s*\n*')
	b = re.compile('</?i>')
	c = re.compile('[\{\<\(\&\#]')
	google.LICENSE_KEY =  "MLh1CuxQFHKb3YFWmom24mcnNsN48nj1"
	url = ""
	if 'query' in request.GET:
		query = request.GET['query']
		try:
			res = Site.objects.get(query=query)
			return render_to_response('mine/getter.html', {'cache': True, 'search': query, 'content': res},
				  context_instance=RequestContext(request))
		except ObjectDoesNotExist:
			data = google.doGoogleSearch(query)
			siteArray = []
			choices = []
			br = Browser()
			br.set_handle_robots(False)
			for site in data.results[:NUM_RESPONSES]:
				try:
					resp = br.open(site.URL)
				except urllib2.HTTPError:
					continue
				soup = BeautifulSoup(resp.read())
				first = a.sub('',soup.prettify())
				sec = b.sub('',first)
				s = BeautifulSoup(sec)
				longest = ""

				for line in s(text=True):
					if not c.search(line):
						if len(line) > len(longest):
							longest = line
				s = Site(url=site.URL,title=site.title,content=longest, query=query)
				siteArray.append(s)
				choices.append(longest)
				longest = ""

			match = ""
			#Compare strings!
			result = ""
			title = ""
			for choice in choices:
				if len(choice) > len(match):
					match = choice

			for sizzite in siteArray:
				if sizzite.content == match:
					result = sizzite
					#Site.objects.get_or_create(url=sizzite.url,query=sizzite.query,content=sizzite.content,title=sizzite.title)
					sizzite.save()
					continue

			return render_to_response('mine/getter.html', {'search': query, 'content': result, 'recent': Site.objects.all()[:4]},
				  context_instance=RequestContext(request))
	else:
		return render_to_response('mine/getter.html', {'recent': Site.objects.all()[:4]},
				  context_instance=RequestContext(request))
